package com.helasasa.maxfunds.lineofcredit.cashloan

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Process
import android.webkit.WebView
import org.json.JSONArray
import org.json.JSONObject


class ProjectApplication : Application() {

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context

        @SuppressLint("StaticFieldLeak")
        lateinit var instance: ProjectApplication

        /** 产品 */
        val mProduct = "HELASASA"

        /** 应用版本 */
        val mAppVersion = "1"

        /** 应用包名 */
        val mPackageName = "com.helasasa.maxfunds.lineofcredit.cashloan"

        /** 应用协议 */
        val mPrivacyPolicy = "https://sites.google.com/view/helasasaprivacy"

        /** 应用商店详情 */
        val mPlayStore = "https://play.google.com/store/apps/details?id=com.helasasa.maxfunds.lineofcredit.cashloan"

        /** 首页额度 */
        var mHomeAmount = "300000"

        /** 运营商类型-法语 */
        var mWalletChannels: MutableList<JSONObject> = mutableListOf()

        /** 测试账号 */
        var mAccUsers: MutableList<JSONObject> = mutableListOf()

        /**
         * 客服列表
         * {title:xxx, type:0电话 1邮箱}
         */
        var mHotlines: MutableList<JSONObject> = mutableListOf()

        /**
         * 启动页权限列表
         */
        val mSplashPermissions: MutableList<String> = mutableListOf()

        /**
         * 首页权限列表
         */
        val mApplyPermissions: MutableList<String> = mutableListOf()

        /**
         * 区号
         */
        var mPhoneCode: String = "+"

        /**
         * 设置联系人列表
         */
        fun updateHotlines(mobiles: String, emails: String) {
            mHotlines.clear()
            val gmobiles: List<String> = mobiles.split(",")
            val gemails: List<String> = emails.split(",")
            for (item in gmobiles) {
                if (item.isNotBlank() and (item.length > 2)) {
                    val obj = JSONObject()
                    obj.put("title", item)
                    obj.put("type", 0)
                    mHotlines.add(obj)
                }
            }

            for (item in gemails) {
                if (item.isNotBlank() and (item.length > 2)) {
                    val obj = JSONObject()
                    obj.put("title", item)
                    obj.put("type", 1)
                    mHotlines.add(obj)
                }
            }
        }

        /**
         * 更新启动页权限
         */
        fun updateSplashPermissions(array: JSONArray?) {
            mSplashPermissions.clear()
            if (array != null) {
                for (index in 0 until array.length()) {
                    val item = array[index] as String
                    if (item.isNotBlank()) {
                        mSplashPermissions.add(item)
                    }
                }
            }
        }

        /**
         * 更新首页权限
         */
        fun updateApplyPermissions(array: JSONArray?) {
            mApplyPermissions.clear()
            if (array != null) {
                for (index in 0 until array.length()) {
                    val item = array[index] as String
                    if (item.isNotBlank()) {
                        mApplyPermissions.add(item)
                    }
                }
            }
        }

        /**
         * 更新首页金额
         */
        fun updateHomeAmount(amount: String) {
            mHomeAmount = amount
        }

        /**
         * 更新运营商类型-法语
         */
        fun updateWalletChannels(array: JSONArray?) {
            mWalletChannels.clear()
            if (array != null) {
                for (index in 0 until array.length()) {
                    val item = array[index] as JSONObject
                    mWalletChannels.add(item)
                }
            }
        }

        /**
         * 更新测试账号列表
         */
        fun updateAccUsers(array: JSONArray?) {
            mAccUsers.clear()
            if (array != null) {
                for (index in 0 until array.length()) {
                    val item = array[index] as JSONObject
                    mAccUsers.add(item)
                }
            }
        }

        /**
         * sp action
         * @param isGet 是否是获取操作
         * @param tv type值字符串
         */
        @SuppressLint("ApplySharedPref")
        fun spAction(kv: String, isGet: Boolean = true, tv: String? = ""): String {
            val spShare = context.getSharedPreferences(mProduct, Context.MODE_PRIVATE)
            if (!isGet) {
                spShare.edit().putString(kv, tv ?: "").commit()
                return tv ?: ""
            }
            return spShare.getString(kv, "") ?: ""
        }

        /**
         * sp action
         * @param isGet 是否是获取操作
         * @param tv type值字符串
         */
        @SuppressLint("ApplySharedPref")
        fun spActionInt(kv: String, isGet: Boolean = true, tv: Int? = 0): Int {
            val spShare = context.getSharedPreferences(mProduct, Context.MODE_PRIVATE)
            if (!isGet) {
                spShare.edit().putInt(kv, tv ?: 0).commit()
                return tv ?: 0
            }
            return spShare.getInt(kv, 0)
        }

        /**
         * name action
         * @param isGet 是否是获取操作
         * @param tk token字符串
         */
        @SuppressLint("ApplySharedPref")
        fun nameAction(isGet: Boolean = true, name: String? = ""): String {
            val keyAction = mProduct + "_NAM"
            return spAction(keyAction, isGet, name)
        }

        /**
         * mobile action
         * @param isGet 是否是获取操作
         * @param tk token字符串
         */
        @SuppressLint("ApplySharedPref")
        fun mobAction(isGet: Boolean = true, mobile: String? = ""): String {
            val keyAction = mProduct + "_MOB"
            return spAction(keyAction, isGet, mobile)
        }

        /**
         * token action
         * @param isGet 是否是获取操作
         * @param tk token字符串
         */
        @SuppressLint("ApplySharedPref")
        fun tkAction(isGet: Boolean = true, tk: String? = ""): String {
            val keyAction = mProduct + "_TK"
            return spAction(keyAction, isGet, tk)
        }

        /**
         * 获取userid
         */
        @SuppressLint("ApplySharedPref")
        fun uidAction(isGet: Boolean = true, uid: String? = ""): String {
            val keyAction = mProduct + "_UID"
            return spAction(keyAction, isGet, uid)
        }

        /**
         * 获取zonepath
         */
        @SuppressLint("ApplySharedPref")
        fun zonePathAction(isGet: Boolean = true, zPath: String? = ""): String {
            val keyAction = mProduct + "_ZPH"
            return spAction(keyAction, isGet, zPath)
        }

        /**
         * 获取评价框展示次数
         */
        @SuppressLint("ApplySharedPref")
        fun reviewDialogAction(isGet: Boolean = true, count: Int? = 0): Int {
            val keyAction = mProduct + "_SRDG"
            return spActionInt(keyAction, isGet, count)
        }

        /** 是否已登录 */
        fun onActionReady(): Boolean {
            val zonePath = zonePathAction(true)
            val tk = tkAction(true)
            return (zonePath.isNotBlank() and tk.isNotBlank())
        }

    }

    override fun onCreate() {
        super.onCreate()
        context = applicationContext
        instance = this

        try {
            // 适配and9 webview配置
            context.autoAdjustWebViewConfig()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

/** 适配android 9网络进程 */
fun Context.autoAdjustWebViewConfig() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        val processName = curAppProcessName()
        if (ProjectApplication.mPackageName != processName) {
            WebView.setDataDirectorySuffix(processName!!)
        }
    }
}

/** 获取进程名称 */
fun Context.curAppProcessName(): String? {
    val activityManager: ActivityManager =
        getSystemService(Application.ACTIVITY_SERVICE) as ActivityManager
    for (processInfo in activityManager.runningAppProcesses) {
        if (processInfo.pid == Process.myPid()) {
            return processInfo.processName
        }
    }
    return getString(R.string.app_name).uppercase()
}